<template>
  <div class="img"   @click="changeImg(index)" :class="{active:detail.isClick}">
    <template v-if="!detail.isEdit">
      <img :src="detail.imgUrl" alt="" model="aspectFit" @click="goDetail(detail)">
      <p style="text-align: left;padding:10rpx 8rpx;box-sizing:border-box;word-break:keep-all;text-overflow: ellipsis;overflow: hidden;">
        {{detail.description?detail.description:'暂未填写'}}
        <van-icon color="#CC0000" v-if="detail.hasChildren" size="14" name="play-circle" /></p>
    </template>
    <template v-if="detail.isEdit">
      <ul class="weui-uploader__files"  v-if="detail.imgUrl">

        <li class="weui-uploader__file weui-uploader__file_status" :class="{'active':detail.progress==100}" style="position: relative;" @click="handleImagePreview('',index)"  >
          <img :src="detail.imgUrl" alt="" style="width: 100%;max-height: 100%">
<!--         <div class="weui-uploader__file-content">{{detail.progress}}%</div>-->
          <van-icon name="close" color="red" @click="remove(index)" size="50rpx" style="position: absolute;bottom:408rpx;right:-16rpx;background: #fff;border-radius: 50%;"/>
        </li>
      </ul>
      <div class="weui-uploader__input-box" style="width: 100%;height: 450rpx;position: relative" v-if="!detail.imgUrl"  @click="upload(detail.id)">
<!--        <input id="uploaderInput" style="width: 100%;" class="weui-uploader__input" type="file" accept="image/*" multiple="">-->
       <p style="position: absolute;bottom:108rpx;left:0;right: 0;text-align: center"><span style="color: rgba(0,0,0,0.5);font-size: 40rpx">上传图片</span></p>
      </div>

<!--      <input type="text" style="height: 70rpx;" ref="myInput" placeholder="请输入标题" v-model.lazy="detail.description"   @change="inputFun">-->
      <van-field
        :value="detail.description"
        placeholder="请输入标题"
        border="false"

        @change="onChange"
      />
    </template>
    <div class="btnBox">

      <!--      <van-button size="small" style="margin-right: 30rpx;" ></van-button>-->
      <van-button icon="edit" size="small" type="primary" @click="updateItem" v-if="!detail.isEdit" style="margin-right: 30rpx;">编辑</van-button>
      <van-button size="small" type="default" @click="outSet" v-else-if="detail.id"  style="margin-right: 30rpx;">取消</van-button>
      <van-button size="small" type="info" @click="submitFun()" v-if="detail.isEdit&&detail.imgUrl" >提交</van-button>
      <van-button size="small" type="danger" @click="delFun()" v-else-if="!detail.isEdit&&detail.imgUrl">删除</van-button>
    </div>
    <van-dialog id="van-dialog" />
    <van-toast id="van-toast" />
  </div>
</template>

<script>
    import * as host from "../utils/api"
    import Dialog from '../../static/vant-weapp/dist/dialog/dialog'
    import Toast from '../../static/vant-weapp/dist/toast/toast';
    export default {
        name: "createBrannerBox",
        props:['detail','index',"isEdit",'pid','dataLength'],
        data(){
            return {
                description: '',
                images: [],
                active_search:true,
                params:[],
                 isFocus:false,
                count:9
            }
        },
        methods:{
          onChange(val){
            this.detail.description=val.mp.detail

          },
          delFun(){//删除
            let that = this;
            Dialog.confirm({
              title: '提示',
              message: '确定删除吗?'
            }).then(() => {
              if(this.detail.hasChildren){
                Dialog.confirm({
                  title: '提示',
                  message: '删除该分类将同时删除下属所有分类,是否继续?'
                }).then(() => {
                  this.delItem();
                }).catch(() => {
                  setTimeout(()=>{
                    this.$emit('changeDom',this.detail.pid)
                    // that.$emit('changeDom',this.detail.pid,that.index)
                  },1000)
                  // on cancel
                });
                // Toast.fail('该分类下有产品无法删除!');
                // wx.showToast({
                //   title: "该分类下有产品无法删除!",
                //   icon: 'none',
                //   duration: 2000,
                //   success:()=>{
                //     //
                //
                //   }

                // })

              }else {

                this.delItem();
              }
              // on confirm
            }).catch(() => {
              // on cancel
            });
          },
            outSet(){
                this.detail.imgUrl=this.detail.detailImg;
                  this.$emit('changeDom',this.detail.pid)
                // this.submitFun()
            },
            goDetail(item){
            //  console.log(item)
                if(item.id){
                  this.$emit('changeData',item)
                    // wx.navigateTo({ url: '/pages/createProductDetail/main?id='+id})
                }

            },
            submitFun () {
                let cartId = wx.getStorageSync('cartId'),
                  userId =  wx.getStorageSync('userId'),
                    that = this;
                if(this.detail.isEdit){
                  if (!this.detail.id) {
                    this.$http.request({
                      method: 'post',
                      url: '/api/material/add',
                      body: {
                        cardId: cartId,
                        imgList:[{
                          description: this.detail.description,
                          imgUrl: this.detail.imgUrl,
                          defaultImg:this.detail.defaultImg
                        }],
                        pid:this.pid||0,
                        userId:userId
                      }
                    }).then((data) => {
                      if (data.code == 200) {
                        wx.showToast({
                          title: '上传成功!',
                          icon: 'success',
                          duration: 2000,
                          success: () => {
                            that.images = []
                            that.description = ''
                            that.detail.isEdit=false;
                            //console.log(this.detail)
                            that.$emit('changeDom',this.pid,that.index)
                          }
                        })
                      }else{
                        wx.showToast({
                          title: `${data.message}`,
                          icon: 'none',
                          duration: 2000
                        })
                      }
                    })
                  } else {
                    this.$http.request({
                      method: 'post',
                      url: '/api/material/update',
                      body: {
                        cardId: cartId,
                        description: this.detail.description,
                        imgUrl: this.detail.imgUrl,
                        id: this.detail.id,
                        pid:this.pid||0,
                        userId:userId
                      }
                    }).then((data) => {
                      if (data.code == 200) {
                        wx.showToast({
                          title: '修改成功!',
                          icon: 'success',
                          duration: 2000,
                          success: () => {
                            that.images = []
                            that.description = ''
                            // that.$emit('changeDom',this.pid,that.index)
                            this.$emit('delChangeDom',this.detail.pid)
                            that.detail.isEdit=false;
                          }
                        })
                      }
                    })
                  }
                }


                // }

            },
            delItem () {
                let that = this;

                if(this.detail.id){
                    this.$http.request({
                        method: 'get',
                        url: '/api/material/delete',
                        body: {
                            materialId: this.detail.id
                        }
                    }).then((data) => {
                        if (data.code == 200) {

                            wx.showToast({
                                title: '提交成功!',
                                icon: 'success',
                                duration: 2000,
                                success: () => {
                                    this.$emit('delChangeDom',this.detail.pid)
                                    // that.getBanner()
                                }
                            })
                        } else {
                            wx.showToast({
                                title: `${data.message}`,
                                icon: 'none',
                                duration: 2000,


                            })
                        }
                    })
                }else{
                    wx.showToast({
                        title: `无法删除` ,
                        icon: 'none',
                        duration: 2000
                    })
                }
                // on confirm


            },
            updateItem(){
                this.isFocus=true;
                this.detail.isEdit=true;
                // setTimeout(()=>{
                //     this.detail.imgUrl="";
                // },10)

                this.$forceUpdate()

            },
            inputFun(val){
                //  console.log(this.detail.description)
                // this.$emit('getDetail',this.detail)
            },
            handleImagePreview (img, index) { // 预览图片
                const idx = index
                const images = this.images
                //  console.log(images)
                wx.previewImage({
                    current: images[idx], // 当前预览的图片
                    urls: images // 所有要预览的图片
                })
            },
            upload (id) {
              this.isVip=wx.getStorageSync('isVip');
              if(id){
                this.commitUploads();
              }else{
                if(this.isVip){
                  this.commitUploads();
                }else{
                  if(this.dataLength>=10){
                    Dialog.confirm({
                      title: '提示',
                      message: '如需上传10张以上,请开通VIP会员!'
                    }).then(() => {
                      wx.navigateTo({ url: `/pages/pay/main` })
                    }).catch(() => {
                      // on cancel
                    });
                  }else{
                    this.commitUpload();
                  }
                }
              }


            },
          commitUploads(e){//vip
            var that = this
            let i = 0
            let upLength // 图片数组长度
            let imgFilePaths
            wx.chooseImage({
              count: this.detail.pid == 0 ? 1 : 9, // 默认9
              sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
              sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
              success: function (res) {

                imgFilePaths = res.tempFilePaths
                upLength = imgFilePaths.length
                    if (that.detail.id && imgFilePaths.length) {
                      that.upLoad(imgFilePaths, i, upLength)
                    } else {
                      imgFilePaths.forEach((a, b) => {
                        that.upLoads(imgFilePaths, b, upLength)
                      })
                    }

                    /**
                     * 上传完成后把文件上传到服务器
                     */
                    wx.showLoading({
                      title: '上传中...'
                    })

              }
            })
          },
          commitUpload(e){
            var that = this
            let i = 0
            let upLength // 图片数组长度
            let imgFilePaths
            wx.chooseImage({
              count: this.detail.pid == 0 ? 1 : 9, // 默认9
              sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
              sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
              success: function (res) {

                imgFilePaths = res.tempFilePaths
                upLength = imgFilePaths.length
                  if(upLength+that.dataLength<=10) {//图片小于十张
                    if (that.detail.id && imgFilePaths.length) {
                      that.upLoad(imgFilePaths, i, upLength)
                    } else {
                      imgFilePaths.forEach((a, b) => {
                        that.upLoads(imgFilePaths, b, upLength)
                      })
                    }

                    /**
                     * 上传完成后把文件上传到服务器
                     */
                    wx.showLoading({
                      title: '上传中...'
                    })
                  }else{//大于十张
                    Dialog.confirm({
                      title: '提示',
                      message: '如需上传10张以上,请开通VIP会员!'
                    }).then(() => {
                      wx.navigateTo({ url: `/pages/pay/main` })
                    }).catch(() => {
                      // on cancel
                    });
                  }



              }
            })
          },
            upLoads (imgPath, i, upLength) {
                let that = this;
                 let params=[];
                let obj=	{
                    "defaultImg": "",
                    "description": "",
                    "imgUrl": "",
                    isClick:false,
                    isEdit:true
                };
                let token = wx.getStorageSync('Authorization')
                // 上传文件
                var upload_task=wx.uploadFile({
                    // url: `${host.host}/api/qiniu/upload`,
                    url: `${host.host}/api/qiniu/upload`,
                    filePath: imgPath[i],
                    name: 'file',
                    header: {
                        'Content-Type': 'multipart/form-data',
                        'Authorization': `Bearer ${token}`
                    },

                    success: function (res) {
                        // that.images.push( JSON.parse(res.data).data)
                        obj.imgUrl= JSON.parse(res.data).data;
                        obj.description=that.detail.description;
                        params.unshift(obj)
                        that.$forceUpdate();
                       // console.log(params)
                        that.$emit('getParams',params)
                      that.detail.description=""
                        wx.showToast({
                            title: '上传成功!',
                            icon: 'success',
                            duration: 2000

                        })

                        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                        // that.files = that.files.concat(imgPath[i]);        //合并图片显示数组
                        // let imgData = JSON.parse(res.data);
                        // that.upImg.push(imgData.data);
                    },
                    fail: function (res) {
                        //  console.log(res)
                        wx.hideLoading()
                        wx.showModal({
                            title: '错误提示',
                            content: '上传图片失败',
                            showCancel: false,
                            success: function (res) { }
                        })
                    }

                })
                upload_task.onProgressUpdate((res)=>{

                    obj.progress=res.progress
                })
            },
            upLoad (imgPath, i, upLength) {
                let that = this
                let token = wx.getStorageSync('Authorization')
                // 上传文件
                var upload_task=wx.uploadFile({
                    // url: `${host.host}/api/qiniu/upload`,
                  url: `${host.host}/api/qiniu/upload`,
                    filePath: imgPath[i],
                    name: 'file',
                    header: {
                        'Content-Type': 'multipart/form-data',
                        'Authorization': `Bearer ${token}`
                    },
                    success: function (res) {

                        // that.images.push( JSON.parse(res.data).data)
                        that.detail.imgUrl= JSON.parse(res.data).data;
                        console.log(that.detail.imgUrl)
                      that.$forceUpdate();
                        // that.$emit('getDetail',that.detail)
                        wx.showToast({
                            title: '上传成功!',
                            icon: 'success',
                            duration: 2000

                        })

                        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                        // that.files = that.files.concat(imgPath[i]);        //合并图片显示数组
                        // let imgData = JSON.parse(res.data);
                        // that.upImg.push(imgData.data);
                    },
                    fail: function (res) {
                        //  console.log(res)
                        wx.hideLoading()
                        wx.showModal({
                            title: '错误提示',
                            content: '上传图片失败',
                            showCancel: false,
                            success: function (res) { }
                        })
                    }

                })
              upload_task.onProgressUpdate((res)=>{
                console.log(res)
              })
            },
            remove (inex) {
              // this.$emit('removeItem',inex)
                this.detail.imgUrl="";
            },
            changeImg(index){
                // this.$emit('getIndex',index)
                // this.detail.forEach((a,i)=>{
                //     a.isClick=false;
                //     if(i==index){
                //         a.isClick=true;
                //     }
                // })
                // this.editData=this.detailListCopy[index];
                // this.$forceUpdate()
                // console.log(this.detailList)
            },
        }
    }
</script>
<style>
  .img .van-cell{
    padding:8rpx 8rpx;
  }
    /*  .img .weui-uploader__file:after {
       content: "";
      position: absolute;
       top: 0;
       right: 0;
       bottom: 0;
       left: 0;
       background-color: rgba(0, 0, 0, 0.5);
       z-index: 100;
      } */
  .img .weui-uploader__file-content{
    font-size: 30rpx;
    color: yellowgreen;
  }
/*  .img .weui-uploader__file.active:after{
    content:"";
    position: absolute;
     top: 0;
     right: 0;
     bottom: 0;
     left: 0;
     background-color: rgba(255, 255, 255, 0.5);
     z-index: -1;
  } */
   .img .weui-uploader__file.active .weui-uploader__file-content{
     display: none;
   }
  .img ._input{
    width:100%;
    /*height: 70rpx;*/
  }
  .img .weui-uploader__file_status:before{
    background-color:transparent ;
  }
  .img .weui-uploader__files{
    width: 100%;
    height:450rpx;
  }
  .img .weui-uploader__files .weui-uploader__file{
    width: 100%;
    height: 450rpx;

  }
</style>
<style scoped>
  .btnBox{
    display: flex;
    justify-content: space-around;
    align-items: center;
  }
  .bannerImg{
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    box-sizing: border-box;
    padding:5%;
  }
  .img{
    width: 45%;
    text-align: center;
    margin-bottom: 40rpx;
    box-sizing: border-box;
    padding-bottom: 10rpx;
    box-shadow: 1px 1px 2px #999;
    border:1px solid transparent;
    border-radius: 10rpx;
  }
  .img.active{
    border-color: rgb(61,176,243);
    border-radius: 10rpx;
  }
  .img img{
    max-width: 100%;
    height:450rpx;
  }

</style>
